<?php

function getHeadImageURL()
{
    global $_G;
    if (isset($_G["profile"])) {
        if (isset($_G["profile"]["head_image_path"]))
            return $_G["profile"]["head_image_path"];
    }
    global $_GCONFIG;
    return $_GCONFIG["user"]["default"]["headimage"];
}

function load_session()
{
    $before = microtime();
    if (isset($_SESSION["isLogined"]) && $_SESSION["isLogined"]) {
        global $_G;
        $_G["isLogined"] = true;
        $_G["login"] = $_SESSION["login"];
        $_G["verify"] = T("user_verify")->fetch_all_by_uid(getSessionUid());
        $_G["profile"] = getProfile(getSessionUid());
        $_G["classdata"] = getClassdata(getSessionUid());
        loadPermission(getSessionUid());
        updateNotReadNoticeAmount();
        updateNotReadLMAmount();
    }
    $after = microtime();
    $_G["loadtime"] = (intval($after) - intval($before));
}

/**
 * 从会话中获取uid
 */
function getSessionUid()
{
    return isset($_SESSION["userid"]) ? $_SESSION["userid"] : false;
}

function checkProfile()
{
    if (! isLogined()) {
        return;
    }
    global $_G;
    if (! isset($_G["profile"])) {
        if (! isAjaxRequest()) {
            if (! (get_get("mod") == "home" && get_get("childmod") == "setting")) {
                header("location:index.php?mod=home&childmod=setting");
            }
        }
    }
}

function isNew($uid = -1)
{
    if ($uid = - 1) {
        global $_G;
        return ! isset($_G["profile"]["name"]);
    }
    $profile = getProfile($uid);
    return ! isset($_G["profile"]["name"]);
}

function getProfile($uid)
{
    return load_head_image(T("user_profile")->fetch_all_by_uid($uid));
}

/**
 * 对已经登陆的用户： 更新会话中的存档信息;
 */
function updateProfileFromDatabase()
{
    if (! isLogined())
        return false;

    $uid = getSessionUid();
    if (! $uid)
        return false;

    global $_G;
    $_G["profile"] = getProfile($uid);
    return true;
}

function load_head_image($profile)
{
    if ($profile) {
        if ($profile["head_image"] != - 1) {
            $profile["head_image_path"] = getResourcePathByRid($profile["head_image"]);
        } else {
            global $_GCONFIG;
            $profile["head_image_path"] = $_GCONFIG["user"]["default"]["headimage"];
        }
    }
    return $profile;
}

function updateProfile($uid, $name, $user_type = "0", $introduce = "这个人很懒没写介绍", $birthday = "2019-07-01 12:00:00", $gender = 0, $motto = "走自己的路让别人无路可走", $head_image = -1)
{
    if ($head_image == - 1) {
        global $_G;
        $head_image = isset($_G["profile"]["head_image"]) ? $_G["profile"]["head_image"] : - 1;
    }
    $profile = array(
        "uid" => $uid,
        "name" => $name,
        "user_type" => $user_type,
        "introduce" => $introduce,
        "birthday" => $birthday,
        "gender" => $gender,
        "motto" => $motto,
        "head_image" => $head_image
    );
    $ignore = array(
        "uid",
        "user_type",
        "gender",
        "head_image"
    );
    T("user_profile")->update($profile, "`uid`='$uid'", $ignore);
    updateProfileFromDatabase();
}

/**
 * 创建个人信息文档
 */
function createProfile($uid, $name, $user_type = "0", $introduce = "这个人很懒没写介绍", $birthday = "2019-07-01", $gender = 0, $motto = "走自己的路让别人无路可走", $head_image = -1)
{
    $profile = array(
        "uid" => $uid,
        "name" => $name,
        "user_type" => $user_type,
        "introduce" => $introduce,
        "birthday" => $birthday,
        "gender" => $gender,
        "motto" => $motto,
        "head_image" => $head_image
    );
    $ignore = array(
        "uid",
        "user_type",
        "gender",
        "head_image"
    );
    T("user_profile")->insert($profile, $ignore);
    updateProfileFromDatabase();
}

function login_session($uid)
{
    global $_G;
    $_SESSION["isLogined"] = true;
    $_SESSION["userid"] = $uid;
    $_SESSION["loginDate"] = date("Y-m-d H:i:s");
    $_SESSION["login"] = T("user_login_data")->fetch_all_by_uid($uid);
    load_session();
}

/**
 * 用户登出
 */
function logout()
{
    if (isLogined()) {
        sessionClose();
        return true;
    }
    return false;
}

/**
 * 用户登录函数，返回state值表示状态，0是成功，-1账户不存在，-2密码错误，-3账户被禁用。1代表已经登录。
 *
 * @param string $account
 * @param int $passwd
 *            状态值
 */
function login($account, $passwd)
{
    $uid = getUID($account);
    $back = judzePassword($account, $passwd, $uid);
    if ($back == 2) {
        directlogin($uid);
        return 0;
    }
    return $back;
}

function judzePassword($account, $passwd, $uid, $ignore_login = false)
{
    global $_G;
    if (isset($_G["isLogined"]) && $_G["isLogined"] && ! $ignore_login) {
        return 1;
    }
    if ($uid == - 1)
        return - 1;
    $salt = T("user_login_data")->getSalt($uid);
    $hash = getPasswordHash($passwd, $salt);
    $state = T("user_login_data")->fetch_ban_state_by_uid_and_passwd($uid, $hash);
    if ($state == - 1)
        return - 2;
    if ($state == 1)
        return - 3;
    return 2;
}

function directlogin($uid)
{
    $sessionid = T("user_login_data")->fetch_session_id($uid);
    if ($sessionid != session_id())
        removeSessionFile($sessionid); // 踢掉跨客户端登陆的
    T("user_login_data")->update_login($uid, getIP(), session_id());
    login_session($uid);
}

/**
 * 根据输入的登录诸如手机号，mail等凭证来调取uid。
 * 不存在则返回-1
 *
 * @param string $account
 * @return int
 */
function getUID($account)
{
    if ($account == "-1") {
        return - 1;
    }
    if (! is_numeric($account)) {
        return T("user_login_data")->fetch_uid_by_mail($account);
    }
    $uid = T("user_login_data")->fetch_uid_by_phone($account);
    return $uid == - 1 ? T("user_login_data")->contain_uid($account) ? $account : - 1 : $uid;
}

/**
 * 注册登录信息
 * 如果是邮箱已经被注册则返回1
 * 如果是手机已经被注册则返回2
 * 成功返回0
 *
 * @param string $password
 *            密码
 * @param string $mail
 *            邮箱
 * @param number $phone
 *            手机
 */
function register_login_info($password, $mail = "-1", $phone = -1, $registerip = "")
{
    if ($mail != "") {
        if (T("user_login_data")->contain_mail($mail))
            return 1;
    } else
        $mail = "-1";

    if ($phone != "") {
        if (T("user_login_data")->contain_phone($phone))
            return 2;
    } else
        $phone = "-1";

    $profile = spawnProfile(dealPassword($password), $mail, $phone, $registerip);
    T("user_login_data")->insert($profile);
    T("user_verify")->insert(array(
        "isphoneverifyed" => 0
    ));
    global $_G;
    $_G["admincache"]["registerUID"] = T("user_login_data")->getUniqueID();

    create_Permission($_G["admincache"]["registerUID"]);
    return 0;
}

/**
 * 处理密码，返回包含盐和处理后hash值的数组
 *
 * @param string $passwd
 *            需要处理的明文密码
 * @return string[] 包含盐和加盐后的hash值的数组
 */
function dealPassword($passwd)
{
    $salt = getSalt();
    $finalHash = getPasswordHash($passwd, $salt);
    return array(
        "password" => $finalHash,
        "salt" => $salt
    );
}

/**
 * 用于处理用户输入的密码，处理后可以直接和数据库进行比对。
 *
 * @param string $passwd
 *            密码原文
 * @param string $salt
 *            盐
 */
function getPasswordHash($passwd, $salt)
{
    return sha256(sha256($passwd) . $salt);
}

/**
 * 随机生成氯化钠
 *
 * @return string 盐
 */
function getSalt()
{
    return sha256(mt_rand(20, 100));
}

function chengePasswd($uid, $passwd)
{
    $salt = getSalt();
    $hash = getPasswordHash($passwd, $salt);
    return T("user_login_data")->update_chenge_passwd($uid, $salt, $hash);
}

/**
 * 生成用户存档
 *
 * @param string[] $passwd
 *            处理后的密码
 * @param string $mail
 *            邮箱地址，默认为空
 * @param number $phone
 *            手机号码 默认为空
 * @param string $registerip
 *            注册ip
 * @return string[] 用户存档
 */
function spawnProfile($passwd, $mail = "", $phone = 1, $registerip = "")
{
    if ($registerip == "") {
        $registerip = getIP();
    }
    return array(
        "password" => $passwd["password"],
        "salt" => $passwd["salt"],
        "registerip" => $registerip,
        "phone" => $phone,
        "mail" => $mail
    );
}

/**
 * 从数据库查询uid为$uid的用户是否已经通过了手机短信验证
 *
 * @param string $uid
 * @return boolean 是否通过
 */
function isVerifyPhone($uid)
{
    return T("user_verify")->isPhoneVerified($uid);
}

/**
 * 从数据库查询uid为$uid的用户是否已经通过了邮箱发送短信验证
 *
 * @param string $uid
 * @return boolean 是否通过
 */
function isVerifyMail($uid)
{
    return T("user_verify")->isMailVerified($uid);
}

/**
 * 重置邮箱验证状态，适用于修改邮箱后重新验证。
 *
 * @param string $uid
 * @return boolean 数据库返回结果 即是否成功
 */
function resetMail($uid)
{
    return T("user_verify")->updateMailVerifyState($uid, 0);
}

/**
 * 重置手机验证状态，适用于修改手机后重新验证。
 *
 * @param string $uid
 * @return boolean 数据库返回结果 即是否成功
 */
function resetPhone($uid)
{
    return T("user_verify")->updatePhoneVerifyState($uid, 0);
}

function sendMail($uid, $verifycode, $mail, $name)
{}

/**
 * 关闭会话，退出登录
 */
function sessionClose()
{
    $_SESSION = array();
    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time() - 3600, '/');
    }
    session_destroy();
}

/**
 * 用户是否登录了
 *
 * @return boolean 是否登录
 */
function isLogined()
{
    return isset($_SESSION["isLogined"]) && $_SESSION["isLogined"] == true;
}

function updateHeadImage($uid, $rid)
{
    $profile = getProfile($uid);
    $head_image = $profile["head_image"];
    if ($head_image != - 1) {
        removeResource($head_image);
    }
    T("user_profile")->update(array(
        "head_image" => $rid
    ), "`uid`='$uid'", array(
        "rid"
    ));
    updateProfileFromDatabase();
}

function getCardInfo($uid)
{
    global $cardInfoCache;
    if (isset($cardInfoCache[$uid])) {
        return $cardInfoCache[$uid];
    }
    $back = array();
    $profile = getProfile($uid);
    if (! $profile) {
        return array();
    }
    $back["head_image_path"] = $profile["head_image_path"];
    $back["name"] = $profile["name"];
    $back["motto"] = $profile["motto"];
    $back["uid"] = $uid;
    $cardInfoCache[$uid] = $back;
    return $back;
}

function getCardInfoByLoginData($account)
{
    $uid = getUID($account);
    if ($uid == - 1) {
        return array();
    }
    return getCardInfo($uid);
}

function getSessionId($uid)
{
    return T("user_login_data")->fetch_sessionid_by_uid($uid);
}

function removeSessionFileByUid($uid)
{
    removeSessionFile(getSessionId($uid));
}

function removeSessionFile($sessionid)
{
    $filename = session_save_path() . "/sess_" . $sessionid;
    if (file_exists($filename))
        return unlink($filename);
    return true;
}

function read_all_Notice($uid)
{
    T("user_notice")->read_all($uid);
}

function read_all_lm($uid)
{
    T("home_leavemessage")->read_all($uid);
}

function sendNotice($uid, $content, $sender = -1)
{
    return T("user_notice")->insert(array(
        "content" => $content,
        "uid" => $uid,
        "sender" => $sender
    ));
}

function getNotReadNotices($uid)
{
    $data = T("user_notice")->fetch_by_uid_not_read($uid);
    if (! $data) {
        return array();
    }
    $back = array();
    foreach ($data as $v) {
        if ($v["sender"] > 0) {
            $sender = $v["sender"];
            $card = getCardInfo($sender);
            $name = $card["name"];
            $senderelec = " <a href='index.php?mod=home&childmod=zone&uid=$sender'>$name</a> ";
            $v["content"] = str_replace("{sender}", $senderelec, $v["content"]);
            $v["card"] = $card;
        }
        $back[$v["nid"]] = $v;
    }
    return $back;
}

function getNoticesLimited($uid, $offset)
{
    $data = T("user_notice")->fetch_by_uid_limited($uid, $offset, 10);
    if (! $data) {
        return array();
    }
    $back = array();
    foreach ($data as $v) {
        if ($v["sender"] > 0) {
            $sender = $v["sender"];
            $card = getCardInfo($sender);
            $name = $card["name"];
            $senderelec = " <a href='index.php?mod=home&childmod=zone&uid=$sender'>$name</a> ";
            $v["content"] = str_replace("{sender}", $senderelec, $v["content"]);
            $v["card"] = $card;
        }
        $back[$v["nid"]] = $v;
    }
    return $back;
}

function updateNotReadNoticeAmount()
{
    global $_G;
    $uid = getSessionUid();
    $_G["noticeamount"] = T("user_notice")->count_not_read($uid);
}

function updateNotReadLMAmount()
{
    global $_G;
    $uid = getSessionUid();
    $_G["notreadlmamount"] = T("home_leavemessage")->count_not_read($uid);
}

function getLogindata($uid)
{
    $data = T("user_login_data")->fetch_login_data_by_uid($uid);
    if (! $data)
        return array();
    $data["full"] = false;
    return $data;
}

function getAllLoginData($uid)
{
    $data = T("user_login_data")->fetch_all_by_uid($uid);
    if (! $data)
        return array();
    unset($data["salt"]);
    unset($data["password"]);
    unset($data["sessionid"]);
    $data["full"] = true;
    return $data;
}

function updateLoginData($uid, $mail, $phone)
{
    T("user_login_data")->update(array(
        "mail" => $mail,
        "phone" => $phone
    ), "`uid`=$uid");
}

function getBandata($uid)
{
    $loginData = getAllLoginData($uid);
    if (! $loginData) {
        return array();
    }
    $profile = getProfile($uid);
    $name = $uid;
    if ($profile) {
        $name = $profile["name"];
    }
    $back = array();
    $back["name"] = $name;
    $back["isbanned"] = $loginData["isbanned"];
    $back["bantime"] = $loginData["bantime"];
    return $back;
}

function updateBanState($uid, $state, $bantime = "1970-01-01 12:00")
{
    T("user_login_data")->update_ban($uid, $state ? 1 : 0, $bantime);
}
?>